<template>
  <div>
    <el-upload
      class="upload-demo"
      :on-success="handleUploadSuccess"
      :on-change="handleChange"
      :show-file-list="false"
      :before-upload="handleBeforeUpload"
      :action="action"
      :http-request="httpRequest"
    >
      <el-button size="small">{{ name }}</el-button>
    </el-upload>
  </div>
</template>

<script>
import axios from 'axios'
import { common } from '@/config'
import { getOss } from '@/utils/alioss'
import { setUpFileName } from '@/hooks'

export default {
  name: 'uploadIcon',
  components: {},
  mixins: [],
  props: {
    name: {
      type: String,
      default: ''
    },
    // 文件类型, 例如['png', 'jpg', 'jpeg']
    fileType: {
      type: Array,
      default: () => []
    },
    // 大小限制(MB)
    fileSize: {
      type: Number
    },
    // 响应处理函数
    responseFn: Function,
    isShowSuccessTip: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      action: '#'
    }
  },
  computed: {},
  watch: {},
  created() {},
  mounted() {},
  destroyed() {},
  methods: {
    async httpRequest({ file }) {
      // 得到文件的内容
      let fileArray = []
      fileArray.push(file)

      let uploadImage = async file => {
        //填写获取签名的地址
        const policyData = await getOss()
        let ossUrl = 'https://oss.wasaiyouxuan.com' //填写自己OSS服务器的地址
        let accessUrl = policyData.objPath + setUpFileName(file) //设置上传的访问路径
        let fromData = new FormData() // 上传文件的data参数

        // form提交
        fromData.append('OSSAccessKeyId', 'LTAI5tATQrBDh3vWLfLAxgHT')
        fromData.append('policy', policyData.policy)
        fromData.append('Signature', policyData.signature)
        fromData.append('bucketName', policyData.bucketName)
        fromData.append('key', accessUrl)
        fromData.append('objPath', policyData.objPath)
        fromData.append('success_action_status', 200)
        fromData.append('file', file)

        await axios.post(ossUrl, fromData)
        return `${ossUrl}/${accessUrl}`
      }

      // 循环上传
      fileArray.forEach(file => {
        uploadImage(file).then(data => {
          this.uploading = false
          if (this.isShowSuccessTip) {
            this.$message.success('上传成功')
          }
          if (this.multiple) {
            if (Array.isArray(this.value)) {
              this.$emit('input', [...this.value, data])
            } else {
              this.$emit('input', [data])
            }
          } else {
            this.$emit('input', data)
          }
        })
      })
    },

    // 上传成功回调
    handleUploadSuccess(response, file) {
      let url = response
      if (this.isShowSuccessTip) {
        this.$message.success('上传成功')
      }
      if (this.responseFn) {
        url = this.responseFn(response, file, this.successFiles)
      }
      this.$emit('input', url)
    },
    handleChange(file, fileList) {
      this.$emit('on-change')
    },
    // 上传前校检格式和大小
    handleBeforeUpload(file) {
      console.log(file)
      let isImg = false
      if (this.fileType.length) {
        let fileExtension = ''
        if (file.name.lastIndexOf('.') > -1) {
          fileExtension = file.name.slice(file.name.lastIndexOf('.') + 1)
        }
        isImg = this.fileType.some(type => {
          if (file.type.indexOf(type) > -1) return true
          if (fileExtension && fileExtension.indexOf(type) > -1) return true
          return false
        })
      } else {
        isImg = file.type.indexOf('image') > -1
      }
      if (!isImg) {
        this.$message.error(`文件格式不正确, 请上传${this.fileType.join('/')}图片格式文件!`)
        return false
      }
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize
        if (!isLt) {
          this.$message.error(`上传头像图片大小不能超过 ${this.fileSize} MB!`)
          return false
        }
      }
      this.uploading = true
      return true
    }
  }
}
</script>

<style scoped></style>
